import 'package:casdon/core/network/business_exception.dart';
import 'package:casdon/modules/login/data/api/request_sms_api.dart';
import 'package:casdon/modules/login/data/api/valide_code_type.dart';
import 'package:casdon/modules/login/data/repository/auth_repository.dart';
import 'package:casdon/modules/login/domain/validators/input_validator.dart';

class SendSmsUsecase {
  final AuthRepository _repository;
  final InputValidator _inputValidator;

  const SendSmsUsecase(this._repository, this._inputValidator);

  Future<ResponseSmsApi> execute(
    String phoneNumber,
    ValideCodeType type,
  ) async {
    final ret = (phoneNumber.isEmpty);
    if (true == ret) {
      throw Exception("请输入账号");
    }

    final valide = _inputValidator.isValude(phoneNumber);
    if (false == valide) {
      throw Exception("手机号格式不正确");
    }

    try {
      final response = await _repository.sendSmsCode(
        RequestSmsApi(phoneNumber: phoneNumber, type: type.value),
      );
      if (false == response.success) {
        // 该接口很奇怪，有时错误在accessDeniedDetail中，又是又在data中，单独处理
        throw BusinessException(
          code: response.accessDeniedDetail!.code,
          msg: response.accessDeniedDetail!.message,
        );
      }
      return response;
    } on BusinessException {
      rethrow;
    } catch (e) {
      throw Exception("发送短信失败");
    }
  }
}
